﻿#region System Namespace
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
#endregion System Namespace

#region Foreign Namespace
using AIMLbot;
#endregion Foreign Namespace

#region Styx Namespace
using Styx;
using Styx.Plugins;
using Styx.Common;
using Styx.CommonBot;
#endregion Styx Namespace

namespace AIMLSay
{
    public class Response
    {
        public readonly string Message;
        public readonly string User;

        public Response(string userName, string message)
        {
            User = userName;
            Message = message;
        }
    }

    public class AIMLSay : HBPlugin
    {
        private Bot _aimlBot;
        private List<Response> _responseList;
        private List<User> _userList;

        public override string Name { get { return "AIMLSay"; } }
        public override string Author { get { return "Giwin"; } }
        public override Version Version { get { return new Version(1, 2); } }
        public override bool WantButton { get { return false; } }

        public string nameOfPlugin = "AIMLSay";
        public string SendChatMessageChatChannel = "Say";
        public string doubleDash = "\\";
        public string mainPath = "Plugins" + "\\" + "AIMLSay" + "\\" + "logs" + "\\";
        public string AIMLPath = "Plugins" + "\\" + "AIMLSay" + "\\" + "aiml";
        public string dayShort = String.Format("{0:dd}", DateTime.Now).ToString();
        public string day = String.Format("{0:dddd}", DateTime.Now).ToString();
        public string month = String.Format("{0:MMMM}", DateTime.Now).ToString();
        public string year = String.Format("{0:yyyy}", DateTime.Now).ToString();
        public string timeSentReceived = string.Format("Date: {0}/{1}/{2} - Time: {3}", DateTime.Now.Day.ToString(), DateTime.Now.Month.ToString(), DateTime.Now.Year.ToString(), DateTime.Now.ToLongTimeString());

        public char[] charsToTrim = { '.' };

        public override void Initialize()
        {
            Logging.Write("[" + nameOfPlugin + "]: " + Version + " " + "Loaded");
            Chat.Say += WoWChatSay; // Hook event
            _aimlBot = new Bot();
            _aimlBot.loadSettings();
            _aimlBot.loadAIMLFromFiles();
            _userList = new List<User>();
            _responseList = new List<Response>();
        }

        public void WoWChatSay(Chat.ChatSimpleMessageEventArgs e)
        {
            User user = _userList.Find(o => o.UserID == e.Args[1].ToString());

            if (user == null)
            {
                user = new User(e.Args[1].ToString(), _aimlBot);
                _userList.Add(user);
            }

            Result result = _aimlBot.Chat(new Request(e.Message, user, _aimlBot));

            if (!_responseList.Contains(new Response(user.UserID, result.Output)))
            {
                if (e.Args[1].ToString() != Styx.StyxWoW.Me.Name && e.Args[0].ToString() != "" && e.Args[0].ToString() != null)
                {
                    _responseList.Add(new Response(user.UserID, result.Output));

                    if (File.Exists(mainPath + doubleDash + year + doubleDash + month + doubleDash + dayShort + doubleDash + day + ".txt"))
                    {
                        using (StreamWriter writer = File.AppendText(mainPath + year + doubleDash + month + doubleDash + dayShort + doubleDash + day + ".txt"))
                        {
                            writer.WriteLine("[" + nameOfPlugin + "] " + string.Format("Date: {0}/{1}/{2} - Time: {3}", DateTime.Now.Day.ToString(), DateTime.Now.Month.ToString(), DateTime.Now.Year.ToString(), DateTime.Now.ToLongTimeString() + " | Received - " + e.Args[1].ToString() + ": " + e.Args[0].ToString()));
                            Logging.Write("[" + nameOfPlugin + "] " + string.Format("Date: {0}/{1}/{2} - Time: {3}", DateTime.Now.Day.ToString(), DateTime.Now.Month.ToString(), DateTime.Now.Year.ToString(), DateTime.Now.ToLongTimeString() + " | Received - " + e.Args[1].ToString() + ": " + e.Args[0].ToString()));
                            if (result.Output.TrimEnd(charsToTrim) != null && result.Output.TrimEnd(charsToTrim) != "" && result.Output.TrimEnd(charsToTrim) != " ")
                                Logging.Write("[" + nameOfPlugin + "] " + string.Format("Date: {0}/{1}/{2} - Time: {3}", DateTime.Now.Day.ToString(), DateTime.Now.Month.ToString(), DateTime.Now.Year.ToString(), DateTime.Now.ToLongTimeString() + " | Sent - " + e.Args[1].ToString() + ": " + result.Output.TrimEnd(charsToTrim)));
                            writer.WriteLine("[" + nameOfPlugin + "] " + string.Format("Date: {0}/{1}/{2} - Time: {3}", DateTime.Now.Day.ToString(), DateTime.Now.Month.ToString(), DateTime.Now.Year.ToString(), DateTime.Now.ToLongTimeString() + " | Sent - " + e.Args[1].ToString() + ": " + result.Output.TrimEnd(charsToTrim)));
                        }
                    }
                    else if (!Directory.Exists(mainPath + doubleDash + year + doubleDash + month + doubleDash + dayShort))
                    {
                        Logging.Write("[" + nameOfPlugin + "]: " + "Directory Created - " + year + "/" + month + "/" + dayShort);
                        Directory.CreateDirectory(mainPath + doubleDash + year + doubleDash + month + doubleDash + dayShort);
                    }
                    else if (!File.Exists(mainPath + doubleDash + year + doubleDash + month + doubleDash + dayShort + doubleDash + day + ".txt") &&
                              Directory.Exists(mainPath + doubleDash + year + doubleDash + month + doubleDash + dayShort))
                    {
                        Logging.Write("[" + nameOfPlugin + "]: " + "File Created - " + year + "/" + month + "/" + dayShort + "/" + day + ".txt");
                        File.Create(mainPath + doubleDash + year + doubleDash + month + doubleDash + dayShort + doubleDash + day + ".txt");
                    }
                }
            }
        }


        private void TrySend(Response response)
        {
            if (response.Message.TrimEnd(charsToTrim) != null)
                if (_responseList.Count > 0 && response.Message != null && response.Message != "")
                    if (response.Message == " " || response.Message == "" || response.Message == null)
                        Thread.Sleep(new Random().Next(4794, 7639));
                    else
                        Styx.WoWInternals.Lua.DoString(String.Format("SendChatMessage(\"{0}\", \"" + SendChatMessageChatChannel + "\", nil, \"{1}\");", response.Message.TrimEnd(charsToTrim), response.User));
            _responseList.Clear();
        }

        public override void Pulse()
        {
            if (StyxWoW.Me == null || !StyxWoW.Me.IsAlive || !StyxWoW.IsInGame || !StyxWoW.IsInWorld) return;

            if (_responseList.Count != 0)
            {
                TrySend(_responseList.First());
            }
        }
    }
}